package JUC;

import io.netty.util.internal.ThreadLocalRandom;
import lombok.*;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

public class CompletableFutureMallDemo {
    static List<NetMell> list = Arrays.asList(
            new NetMell("jd"),
            new NetMell("tb"),
            new NetMell("tb"),
            new NetMell("tb"),
            new NetMell("tb"),
            new NetMell("tb"),
            new NetMell("dd")
    );

    /**
     * 一家家搜
     * @param list
     * @return
     */
    public static List<String> getPrice(List<NetMell> list,String productName){
       return list.stream().map(netMell -> String.format(productName+"in %s price is %.2f",netMell.getName(),netMell.calcPrice(productName))).collect(Collectors.toList());
    }

    public static List<String> getPriceByCompletableFuture(List<NetMell> list,String productName){
         return list.
                stream().
                map(
                        netMell -> CompletableFuture.supplyAsync(()->String.format(productName+"in %s price is %.2f",
                                netMell.getName(),
                                netMell.calcPrice(productName))))
                .collect(Collectors.toList())
                 .stream().map(e->e.join()).collect(Collectors.toList());
    }
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        long startTime1=System.currentTimeMillis();
        List<String> mysql1 = getPrice(list, "mysql");

        mysql1.forEach(System.out::println);
        long endTime1=System.currentTimeMillis();
    System.out.println("-------costTime:"+(endTime1-startTime1)+"毫秒");

        long startTime2=System.currentTimeMillis();
        List<String> mysql2 = getPriceByCompletableFuture(list, "mysql");

        mysql2.forEach(System.out::println);
        long endTime2=System.currentTimeMillis();
        System.out.println("-------costTime:"+(endTime2-startTime2)+"毫秒");

    }

}

class NetMell{
    @Getter
    private String name;
 public NetMell(String name){
     this.name=name;
 }
 public Double calcPrice(String productName){
     try {TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {throw new RuntimeException(e);}
     return ThreadLocalRandom.current().nextDouble()*2+productName.charAt(0);
 }

}